// pages/order-all/order-all.js
import {OrderStatus} from "../../utils/const.js"
const orderService =  require( '../../services/order/orderService.js');

var app = getApp();
Page({
  page: {
    size: 5,
    num: 1,
  },

  data: {
    tabs: [
      { key: -1, text: '全部' },
      { key: OrderStatus.PENDING_PAYMENT, text: '未付款', info: '' },
      { key: OrderStatus.PENDING_DELIVERY, text: '已付款', info: '' },
      { key: OrderStatus.COMPLETE, text: '已完成', info: '' },
      { key: OrderStatus.PENDING_REFUND, text: '退单/售后', info: '' },
      { key: OrderStatus.PENDING_COMMENT, text: '评价', info: '' },
    ],
    curTab: -1,
    orderList: [],
    pageInfo: null, // 分页查询显示
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg:
      'http://www.breakfast-dinner.xin/chb_eatery_images/empty-order-list.png',
    backRefresh: false,
    status: -1,
  },

  onTabChange(e) {
    const { value } = e.detail;
    const tab = this.data.tabs.find((v) => v.key === value);
    if (!tab) return;
    var that = this;
    this.setData({status: value,}, ()=>{
      that.refreshList(value);
    })
  },

  refreshList(status = -1, reset=true) {
    if(1 === this.data.listLoading){
      // 正在刷新，先不刷新
      return;
    }
    var that = this;
    this.setData({
      curTab: status,
    });

    if(reset || !this.data.pageInfo){
      this.setData({
        orderList: [],
        pageInfo: null
      });
      this.page = {
        size: 10,
        num: 1,
      };
    }else{
      // if(this.data.orderList?.length >= this.data.pageInfo?.total){
      //   this.setData({
      //     listLoading: 2  // no more order
      //   })
      //   console.log('no more order: ', this.data.orderList?.length, this.data.pageInfo?.total)
      // }
      this.page = {
        size: 10,
        num: this.data.pageInfo.pageNum > this.data.pageInfo.pages?this.data.pageInfo.pages + 1 :this.data.pageInfo.pageNum + 1,
      };
    }
    return this.getAfterServiceList(status, reset);
  },

  _reloginCallback(){
    console.log('在_reloginCallback中', this.data)
    this.getAfterServiceList();
  },

  getHistoryOrdersPromise(){
    var that = this;
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.data.global_urls.getHistoryOrdersUrl(),
        method: 'GET',
        header: {
          'Authorization': `Bearer ${app.data.loginData.token}`,
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: {
          pageNo: this.page.num,
          pageSize: this.page.size,
          orderType: this.data.status
        },
        success: (res) => {
          console.log(res);
          resolve(res.data);
        },
        fail(e){
          console.log(e);
          reject(e)
        },
        complete(e){
        }
      });
    });
  },

  getAfterServiceList(statusCode = -1, reset = false) {
    var that = this;
    
    this.setData({
      listLoading: 1,
    });

    return this.getHistoryOrdersPromise().then((res) => {
      if(res.status === 10024){
        // 重新登录
        app._needReLogin(null, that._reloginCallback.bind(that))
      }else if(10000 == res.status){
        // success
        if(res.data && 
          res.data.list &&
          0 !== res.data.list.length &&
          (that.data.pageInfo?that.data.pageInfo.pageNum < res.data.pageNum:1)
        ){
          that.setData({
            orderList: (reset?res.data.list:that.data.orderList.concat(res.data.list)),
            complete(){

            }
          })
        }else{
          
        }
          
        that.setData({
          // orderList: [],
          pageInfo: res.data
        })
      }

      if(that.data.pageInfo && that.data.pageInfo.pageNum >= that.data.pageInfo.pages){
        // no more orders
        that.setData({
          listLoading: 2,
        });
      }else{
        that.setData({
          listLoading: 0,
        });
      }
    }).catch((e)=>{
      that.setData({
        listLoading: 3,
      });
    })
  },

  navigatorToOrderDetail(e){
    let order = e.currentTarget.dataset.order;
    console.log('导航到订单详情：', e.currentTarget.dataset.order)
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderNo=${order.orderNo}`,
    })
  },

  onBack() {
    wx.navigateBack()
  },

  onGoHome() {
    wx.reLaunch({
      url: '/pages/home/home',
    });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    // this.refreshList(status);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    let status = parseInt(query.status);
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : -1;
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('-------------in onShow-----------------')
    this.refreshList(this.data.status);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh(e) {
    var that = this;
    // const { callback } = e.detail;
    this.setData({
      pullDownRefreshing: true,
    }); // 下拉刷新时不显示load-more
    this.refreshList(this.data.status, true).then(()=>{
      console.log('停止下拉');
      that.setData({
        pullDownRefreshing: false,
      }); // 下拉刷新时不显示load-more
      wx.stopPullDownRefresh();
    })
  },


      /**
[🛍️]  # 左侧图标区域（店铺Logo/类型图标）
------------------------------------------
🍔 肯德基（人民广场店）  
订单号：202310051234 | 序号：A12  
🚚 外卖配送中 | 预计14:45送达  
💴 总价：￥89 | 🟢 已完成  
📅 更新时间：2023-10-05 14:30  

🚚 外卖 → 餐盒+运输图标
🍽️ 堂食 → 刀叉图标
📦 自提 → 手提袋图标
       * 
       */
  /**
   * 页面上拉触底事件的处理函数
   */
  onScrollToLower() {
    console.log('-------------onScrollToLower------------------')
    this.refreshList(this.data.status, false);
  },

  onReTry(){
    console.log('点击了刷新')
    this.refreshList(this.data.status, false);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  handleCancelOrder(e){
    console.log('取消订单按钮', e)
    let order = e.currentTarget.dataset.order;
    let index = e.currentTarget.dataset.index;
    var that = this;

    orderService.cancelOrderWithInteractive(order).then((order) => {
      let dataToUpdate = {};
      // 使用方括号语法动态构建数据路径
      dataToUpdate[`orderList[${index}].order.orderStatus`] = order.orderStatus;
      that.setData(dataToUpdate);

      // wx.navigateTo({
      //   url: `/pages/order-detail/order-detail?orderNo=${order.orderNo}`,
      // })
    })
  },

  toPayByOrder(e){
    console.log('去支付', e)
    let order = e.currentTarget.dataset.order;
    orderService.toPayByOrder(order, (()=>{
      wx.navigateTo({
        url: `/pages/order-detail/order-detail?orderNo=${order.orderNo}`,
      })
    }).bind(this));
  },

  handleRefund(e){
    let order = e.currentTarget.dataset.order;
    let index = e.currentTarget.dataset.index;
    var that = this;
    orderService.orderRefundPromise(order).then((res)=>{
      let order = res.data;
      let dataToUpdate = {};
      // 使用方括号语法动态构建数据路径
      dataToUpdate[`orderList[${index}].order.orderStatus`] = order.orderStatus;
      that.setData(dataToUpdate);
      // wx.navigateTo({
      //   url: `/pages/order-detail/order-detail?orderNo=${order.orderNo}`,
      // })
    })
  },
  
  handleCancelRefund(e){
    let order = e.currentTarget.dataset.order;
    let index = e.currentTarget.dataset.index;
    var that = this;
    orderService.cancelRefundPromise(order).then((res)=>{
      let order = res.data;
      let dataToUpdate = {};
      // 使用方括号语法动态构建数据路径
      dataToUpdate[`orderList[${index}].order.orderStatus`] = order.orderStatus;
      that.setData(dataToUpdate);
    })
  },

  handleMoreOrder(e){
    console.log('再来一单', e)
    wx.reLaunch({
      url: '/pages/index/index',
    });
  },

  handleAddOrderToCart(e){
    console.log('加入购物车', e)
    let order = e.currentTarget.dataset.order;
    let index = e.currentTarget.dataset.index;
    var that = this;
    orderService.addOrderToCart(this.data.orderList[index].orderDetail
      , this.data.orderList[index].order.postType)
  },

})